package com.shu.qq.component.tcp;

import io.netty.channel.*;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component("chatChannelInitializer")
@Slf4j
public class ChatChannelInitializer extends ChannelInitializer<NioSocketChannel> {

    @Override
    protected void initChannel(NioSocketChannel ch) throws Exception {
        //TODO:设置handler解析
        ch.pipeline().addLast(new StringDecoder());
        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
            @Override
            protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                Channel channel = ctx.channel() ;
                log.info("检查ctx = {} ,检查channel = {},检查initChannel = {} 接收到来自{}的消息--> {}",ctx.hashCode(),channel.hashCode(),ch.hashCode(),channel.remoteAddress(),msg);
            }
        });
        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
            @Override
            public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
                super.channelRegistered(ctx);
                log.info("channel = {} 的{} 连接建立",ctx.channel().hashCode(), ctx.channel());
            }

            @Override
            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                super.channelInactive(ctx);
                log.info("channel = {} 的{} 已经断开",ctx.channel().hashCode(), ctx.channel());
                ctx.close();
            }
        });
    }
}
